import java.security.MessageDigest
import org.codehaus.groovy.grails.commons.ConfigurationHolder


class TokenBuilderService {

  boolean transactional = true

  def public static tokens = [:];

  def seedValue = "BUBBAAAAHASH"

  def seedKey = "10293857604943"

  def expirationMillis = 10000



  def TokenBuilderService(expirationMillis, seedValue, seedKey) {
    this.expirationMillis = expirationMillis;
    this.seedValue = seedValue;
    this.seedKey = seedKey;
  }



  def TokenBuilderService() {

    if (ConfigurationHolder.config.antiCSRF.expirationMillis) {
        this.expirationMillis = ConfigurationHolder.config.antiCSRF.expirationMillis
    }
     if (ConfigurationHolder.config.antiCSRF.seedKey) {
        this.expirationMillis = ConfigurationHolder.config.antiCSRF.seedKey
    }
    if (ConfigurationHolder.config.antiCSRF.seedValue) {
        this.expirationMillis = ConfigurationHolder.config.antiCSRF.seedValue
    }
  }


  def buildToken() {

    MessageDigest digest = MessageDigest.getInstance("SHA1")

    digest.update(String.valueOf(seedKey + new Date().getTime()).bytes) 

    def keyDigest = new BigInteger(1, digest.digest()).toString(16).padLeft( 40, '0' )
      digest.update(String.valueOf(seedValue + new Date().getTime()).bytes)

    def valueDigest =  new BigInteger(1, digest.digest()).toString(16).padLeft( 40, '0' )
    def expmillis = expirationMillis + new Date().getTime();

    def token = new AntiCsrfToken(value: valueDigest, name: keyDigest, expiration : expmillis)
    tokens[keyDigest] = token
    return token
  }

  def checkToken(AntiCsrfToken token){
       def expmillis = new Date().getTime();
       return expmillis < token.expiration

  }

  def pruneExpiredToken(){

   def keylist = new HashSet( tokens.keySet())

   keylist.each {key -> log.debug(key)
       if(!checkToken(tokens[key])){
          tokens.remove(key)
       }

    }
  }

}
